package com.JavaNet.chapter7_urlConnection;

import java.io.*;
import java.net.*;

/**
 * @author harold
 * <p>
 * 示例 7 - 16
 * 包括响应码和消息的 html 源代码查看程序
 */
public class SourceViewer3 {

    public static void main(String[] args) {

        try {
            // Open the URLConnection for reading
            URL u = new URL("https://www.baidu.com");
            HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection();
            int code = urlConnection.getResponseCode();
            String response = urlConnection.getResponseMessage();
            System.out.println("HTTP/1.x " + code + " " + response);
            for (int j = 1; ; j++) {
                String header = urlConnection.getHeaderField(j);
                String key = urlConnection.getHeaderFieldKey(j);
                if (header == null || key == null) break;
                System.out.println(urlConnection.getHeaderFieldKey(j) + ": " + header);
            }
            System.out.println();

            try (InputStream in = new BufferedInputStream(urlConnection.getInputStream())) {
                // chain the InputStream to a Reader
                Reader r = new InputStreamReader(in);
                int c;
                while ((c = r.read()) != -1) {
                    System.out.print((char) c);
                }
            }
        } catch (MalformedURLException ex) {
            System.err.println(args[0] + " is not a parseable URL");
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }

}
